#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "../include/serviceAnalysis.h"
#include "../include/wrap.h"

#define MAXLINE 80
#define SERV_PORT 8000

int main(void) {

	struct sockaddr_in servaddr,cliaddr;
	socklen_t cliaddr_len;
	int listenfd,connfd;	
	int m;

	//List *mlist = CreateList();
	//List *slist = CreateList();
	//List *clist = CreateList();
	//readid(mlist, "../manager/id.txt");
	//readid(slist, "../servce/id.txt");
	//readid(clist, "../custom/id.txt");

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;				//ipv4
	servaddr.sin_port = htons(SERV_PORT);			//port 8000
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);		//0.0.0.0
	
	Bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
	
	Listen(listenfd,20);

	printf("Accepting connection ... \n");

	while (1) {
		cliaddr_len = sizeof(cliaddr);
		
		connfd = Accept(listenfd, (struct sockaddr *) &cliaddr, &cliaddr_len);
		
		printf("received from %s at PORT %d\n", 
			inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
		
		m = fork();
		if (m == -1){

			printf("vfork error\n");
			continue;
		} else if (m == 0){
		
			char buf[MAXLINE];
			int n,i;

			close(listenfd);			
			
			while ((n = Read(connfd, buf, MAXLINE)) != 0){
				
				buf[n] = '\0';
				Execute_the_order(buf, connfd);
			}

			
			printf("the client is closed\n");
			Close(connfd);
			exit(0);		
		} 
			
		
	}	
		
	
	return 0;
}
